package mysql

import (
	"context"
	"fmt"
	"log"
	"mysql-read-excel/config"
	"os"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

//数据库连接(首字母不大写, 不直接提供调用, 通过 Get() Get2() 获取)
var dbMysql *gorm.DB

// InitializeDatabase mysql连接初始化
func InitializeDatabase() (err error) {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second, // 慢 SQL 阈值
			LogLevel:                  logger.Info, // 日志级别
			IgnoreRecordNotFoundError: true,        // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  true,        // 禁用彩色打印
		},
	)
	//data source name
	//用户名@密码@协议(ip:port)/数据库
	mysqlConfig := config.SystemConfig.MysqlConfig
	connArgs := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true&loc=Local&charset=utf8&multiStatements=true",
		mysqlConfig.User, mysqlConfig.Passwd, mysqlConfig.Ip, mysqlConfig.Port, mysqlConfig.Database)
	dbMysql, err = gorm.Open(mysql.Open(connArgs), &gorm.Config{
		//日志配置
		Logger: newLogger,
		//自定义表名格式
		NamingStrategy: schema.NamingStrategy{
			//自定义表名前缀 t_ tb_ 等等
			TablePrefix: "",
			//单数模式(表名后不加s)
			SingularTable: true,
		},
	})
	if err != nil {
		panic(err)
	}
	return nil
}

// Get 返回mysql连接
func Get() *gorm.DB {
	if dbMysql == nil {
		log.Fatal("database has not been initialized")
	}
	return dbMysql
}

// Get2 返回mysql连接, 推荐使用这个, 独立上下文
func Get2(ctx context.Context) *gorm.DB {
	if dbMysql == nil {
		log.Fatal("database has not been initialized")
	}
	return dbMysql.WithContext(ctx)
}
